import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react'
import { useLocation } from 'react-router-dom'

interface HistoryItem {
  label: string
  path: string | null
  primary: boolean
  closable: boolean
}

interface HistoryContextType {
  history: HistoryItem[]
  removeHistory: (label: string) => void
  clearHistory: () => void
  maxHistoryItems: number
  setMaxHistoryItems: (max: number) => void
}

const HistoryContext = createContext<HistoryContextType | undefined>(undefined)

// 页面路由映射（从现有路由获取）
const pageRoutes: Record<string, string> = {
  '/cell-config': '细胞类型',
  '/populations': '细胞群体',
  '/syn-mechs': '突触机制',
  '/conn-rules': '连接规则',
  '/subcell-conn-rules': '亚细胞连接规则',
  '/stim-sources': '刺激源',
  '/stim-targets': '刺激目标',
  '/simulation-config-general': '仿真配置-通用',
  '/simulation-config-record': '仿真配置-记录',
  '/simulation-config-network': '仿真配置-网络',
  '/simulation-config-network-v2': '仿真配置-网络V2',
  '/simulation-config-network-editor': '仿真配置-编辑器',
  '/simulation-config-save': '仿真配置-保存',
  '/simulation-config-save-v2': '仿真配置-保存V2',
  '/plot-settings-raster': '绘图-光栅图',
  '/plot-settings-trajectory': '绘图-轨迹图',
  '/plot-settings-lfp': '绘图-LFP',
  '/reaction-diffusion-region': '反应扩散-区域',
  '/reaction-diffusion-empty': '反应扩散-空',
  '/import-neuroml': '导入NeuroML',
  '/import-python': '导入Python',
  '/experiment-manager': '实验管理器',
  '/select-folder': '选择文件夹',
  '/open-json': '打开JSON',
  '/save-json': '保存JSON',
  '/save-json-options': '保存JSON选项',
  '/delete-confirm': '删除确认',
}

// 兼容旧路由（frame 路由 + 历史遗留路径）
const legacyRouteMapping: Record<string, string> = {
  '/synaptic-mechanisms': '/syn-mechs',
  '/connectivity-rules': '/conn-rules',
  '/subcellular-connectivity': '/subcell-conn-rules',
  '/stimulation-sources': '/stim-sources',
  '/stimulation-targets': '/stim-targets',
  '/plot-settings-traces': '/plot-settings-trajectory',
  '/reaction-diffusion-extracellular': '/reaction-diffusion-empty',
  '/frame/8': '/cell-config',
  '/frame/10': '/simulation-config-general',
  '/frame/13': '/plot-settings-raster',
  '/frame/14': '/plot-settings-trajectory',
  '/frame/15': '/reaction-diffusion-region',
  '/frame/16': '/plot-settings-lfp',
  '/frame/17': '/reaction-diffusion-empty',
  '/frame/18': '/simulation-config-record',
  '/frame/19': '/simulation-config-network',
  '/frame/20': '/simulation-config-save',
  '/frame/21': '/simulation-config-network-v2',
  '/frame/22': '/simulation-config-save-v2',
  '/frame/23': '/import-neuroml',
  '/frame/24': '/simulation-config-network-editor',
  '/frame/25': '/experiment-manager',
  '/frame/26': '/select-folder',
  '/frame/27': '/open-json',
  '/frame/28': '/save-json',
  '/frame/29': '/delete-confirm',
  '/frame/30': '/save-json-options',
  '/frame/31': '/import-python',
}

interface HistoryProviderProps {
  children: ReactNode
}

// 获取页面标签名称
function getPageLabel(path: string): string {
  // 先检查是否是 frame 路由，转换为新路由
  const normalizedPath = legacyRouteMapping[path] || path
  return pageRoutes[normalizedPath] || '未知页面'
}

export function HistoryProvider({ children }: HistoryProviderProps) {
  const location = useLocation()

  // 历史记录最大条数，默认20个
  const [maxHistoryItems, setMaxHistoryItems] = useState<number>(20)

  // 默认显示20个常用模块
  const defaultHistory: HistoryItem[] = [
    { label: '细胞类型', path: '/cell-config', primary: true, closable: true },
    { label: '仿真配置-通用', path: '/simulation-config-general', primary: false, closable: true },
    { label: '仿真配置-记录', path: '/simulation-config-record', primary: false, closable: true },
    { label: '仿真配置-保存', path: '/simulation-config-save', primary: false, closable: true },
    { label: '仿真配置-网络', path: '/simulation-config-network', primary: false, closable: true },
    { label: '群体', path: '/populations', primary: false, closable: true },
    { label: '突触机制', path: '/syn-mechs', primary: false, closable: true },
    { label: '连接规则', path: '/conn-rules', primary: false, closable: true },
    { label: '亚细胞连接规则', path: '/subcell-conn-rules', primary: false, closable: true },
    { label: '刺激源', path: '/stim-sources', primary: false, closable: true },
    { label: '刺激目标', path: '/stim-targets', primary: false, closable: true },
    { label: '绘图-光栅图', path: '/plot-settings-raster', primary: false, closable: true },
    { label: '绘图-LFP', path: '/plot-settings-lfp', primary: false, closable: true },
    { label: '绘图-轨迹', path: '/plot-settings-trajectory', primary: false, closable: true },
    { label: '反应扩散-区域', path: '/reaction-diffusion-region', primary: false, closable: true },
    { label: '反应扩散-外向电流', path: '/reaction-diffusion-empty', primary: false, closable: true },
    { label: '实验管理器', path: '/experiment-manager', primary: false, closable: true },
    { label: '打开JSON', path: '/open-json', primary: false, closable: true },
    { label: '导入Python', path: '/import-python', primary: false, closable: true },
    { label: '导入NeuroML', path: '/import-neuroml', primary: false, closable: true },
  ]

  const [history, setHistory] = useState<HistoryItem[]>(defaultHistory)

  useEffect(() => {
    const rawPath = location.pathname
    const path = legacyRouteMapping[rawPath] || rawPath

    // 跳过首页
    if (path === '/' || path === '') {
      return
    }

    // 获取页面标签
    const pageLabel = getPageLabel(path)

    // 如果是未知页面，不添加到历史记录
    if (pageLabel === '未知页面') {
      return
    }

    setHistory((prev) => {
      // 检查是否已存在该页面
      const existingIndex = prev.findIndex((item) => item.path === path || item.label === pageLabel)

      if (existingIndex >= 0) {
        // 如果存在，将其设为 primary，其他设为 false
        return prev.map((item, index) => ({
          ...item,
          primary: index === existingIndex,
        }))
      } else {
        // 如果不存在，添加新页面到开头
        const newItem: HistoryItem = {
          label: pageLabel,
          path: path,
          primary: true,
          closable: true,
        }

        // 将其他项的 primary 设为 false
        const updatedPrev = prev.map((item) => ({ ...item, primary: false }))

        // 添加新项到开头，并限制最大数量
        const newHistory = [newItem, ...updatedPrev]

        // 如果超过最大数量，移除最后的项
        if (newHistory.length > maxHistoryItems) {
          return newHistory.slice(0, maxHistoryItems)
        }

        return newHistory
      }
    })
  }, [location.pathname, maxHistoryItems])

  const removeHistory = (label: string) => {
    setHistory((prev) => {
      const filtered = prev.filter((item) => item.label !== label)
      // 如果删除的是primary项，设置第一项为primary
      if (filtered.length > 0 && !filtered.some((item) => item.primary)) {
        filtered[0].primary = true
      }
      return filtered
    })
  }

  const clearHistory = () => {
    setHistory(defaultHistory)
  }

  return (
    <HistoryContext.Provider
      value={{
        history,
        removeHistory,
        clearHistory,
        maxHistoryItems,
        setMaxHistoryItems
      }}
    >
      {children}
    </HistoryContext.Provider>
  )
}

export function useHistory() {
  const context = useContext(HistoryContext)
  if (context === undefined) {
    throw new Error('useHistory must be used within a HistoryProvider')
  }
  return context
}

